<template>
  <div class="login">
    <div class="login-weaper">
      <div class="login-right">
        <div class="login-main" v-if="loginType == 3">
          <!-- <h4 class="login-title">User Permission Management</h4> -->
          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="el-form login-form"
          >
            <el-form-item style="margin-left: 0px" prop="userName">
              <div style="font-size: 18px; font-weight: 500">User ID</div>
              <el-input
                prefix-icon="el-icon-user"
                v-model="loginForm.userName"
                clearable
                autocomplete="off"
                @input="PermissionFocus"
                @clear="UserClear"
              >
              </el-input>
            </el-form-item>
            <el-form-item style="margin-left: 0px" prop="Permission">
              <div style="font-size: 18px; font-weight: 500">Permission</div>
              <el-select
                v-model="loginForm.Permission"
                placeholder="Please select"
                autocomplete="new-password"
                multiple
                clearable
              >
                <el-option
                  v-for="item in PermissionList"
                  :key="item.RoleId"
                  :label="item.RoleName"
                  :value="item.RoleId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="margin: 40px 0px 0">
              <el-button
                type="primary"
                class="login-submit"
                @click="submitForm"
                @keyup.enter="onKeyUp(e)"
              >
                <span style="font-size: 18px; font-weight: 500">Save</span>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <el-dialog
      title="选择产线 | 投料点"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <sel-work-bench @getWorKBenchValue="getWorKBenchValue"></sel-work-bench>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="proSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from "element-ui";
import { formatDate, formatAxis } from "@/utils/formatTime";
import { api } from "@/utils/api";
import Base64 from "@/utils/Base64.js";
import SelWorkBench from "@/components/SelWorkBench.vue";
import { comparedArr, PrintInit } from "@/utils/tools";

export default {
  name: "login",
  components: {
    SelWorkBench,
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      // console.log('value',value);
      if (value.length < 1) {
        callback(new Error("Please select Permission"));
      } else {
        callback();
      }
    };
    return {
      isView: false,
      dialogVisible: false,
      PermissionList: [],
      typingTimeout: null,
      productionLine: "",
      Put_Rule: "",
      loginForm: {
        userName: "",
        // password: "",
        Permission: "",
      },
      loginRules: {
        userName: [
          {
            required: true,
            message: "Please enter User ID",
            trigger: "blur",
          },
        ],
        Permission: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        // Permission: [
        //   { required: true, trigger: "blur", validator: validatePassword },
        // ],
      },
      telLoginForm: {
        phone: "",
        password: "",
      },
      telLoginRules: {
        phone: [
          {
            required: true,
            // message: this.$t("login.phoneRuleMsg1"),
            trigger: "blur",
          },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            // message: this.$t("login.phoneRuleMsg2"),
            trigger: "blur",
          },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      loginType: 3,
      getThemeConfig: {},
      route: "/",
      time: {
        txt: "",
        fun: null,
      },
      version: "V1.2.1",
      PublicKey:
        "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmEXJf0ehzAPBlpsptktB3ao86OGeTyAA4Qz1mscfUU1ZYU165mjcZwImyzsNM40KDT3/h8Cltht++Qr9zKpZG2bMN7Vk1vzn4xBrZteFdL6mOcsXjIulEd8veTnl/0Hh+pGfJelijJWWanskVDN7nv2ud9WpwEn+exHh45JOy/QIDAQAB-----END PUBLIC KEY-----",
    };
  },
  computed: {
    // 获取当前时间
    currentTime() {
      return formatAxis(new Date());
    },
    // 获取布局配置信息
    // getThemeConfig() {
    // 	return this.$store.state.themeConfig.themeConfig;
    // },
  },
  mounted() {
    this.initTime();
    // this.showProductionLine();
    window.addEventListener("keydown", this.onKeyUp);
    document.title = "User Permission";
  },
  methods: {
    UserClear() {
      this.loginForm.Permission = [];
      this.PermissionList = [];
    },
    PermissionFocus() {
      console.log("focus");
      clearTimeout(this.typingTimeout);
      this.typingTimeout = setTimeout(() => {
        this.UserRolesGet();
        // 在这里触发你的事件处理逻辑
      }, 500); // 延迟时间（毫秒）
    },
    async UserRolesGet() {
      this.UserClear();
      this.loginForm.userName = this.loginForm.userName.trim();
      const params = { userId: this.loginForm.userName };
      if (this.loginForm.userName) {
        let [ERR, GRES] = await api.UserRolesGet(params);
        if (GRES.code === 0) {
          console.log("UserRolesGet", GRES);
          this.PermissionList = GRES.data;
          this.loginForm.Permission = GRES.data
            .filter((m) => m.Selected == 1)
            .map((m) => m.RoleId);
        }
      }
    },
    // 缓存的产线|工位 有就直接显示
    showProductionLine() {
      const workBenchCode = localStorage.getItem("workBench");
      if (workBenchCode) {
        console.log("xxxxxx", workBenchCode);
        const isThere = this.hasStationsPoints(workBenchCode);
        if (isThere)
          this.productionLine = localStorage.getItem("workBenchName");
      }
    },
    // 初始化左上角时间显示
    initTime() {
      // this.time.txt = formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS WWW QQQQ');
      this.time.txt = formatDate(new Date(), "YYYY-mm-dd HH:MM:SS");
      this.time.fun = setInterval(() => {
        this.time.txt = formatDate(new Date(), "YYYY-mm-dd HH:MM:SS");
      }, 1000);
    },
    planPullBreakup() {
      let LcWorkBench = localStorage.getItem("workBench");
      if (LcWorkBench) {
        LcWorkBench = JSON.parse(LcWorkBench);
      }
      const [ProductLineCode, PointCode] = LcWorkBench;
      const params = {
        data: {
          UserId: this.loginForm.userName,
          ProductLineCode,
          PointCode,
        },
      };
      api.planPullBreakupAPI(params).then((res) => {
        console.log("planPullBreakup----->>>", res);
      });
    },
    onKeyUp(e) {
      if (e.keyCode === 13) {
        this.submitForm();
      }
    },
    proSure() {
      this.dialogVisible = false;
      this.showProductionLine();
    },
    getWorKBenchValue(data) {
      this.productionLine = data;
    },
    selProductionLine() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    // 精定位还是物料车
    isMaterialCar() {
      const PL = JSON.parse(localStorage.getItem("ProductList"));
      let LcWorkBench = localStorage.getItem("workBench");
      let findSelf = {};
      if (LcWorkBench) {
        LcWorkBench = JSON.parse(LcWorkBench);
      }
      const [ProductLineCode, PointCode] = LcWorkBench;
      let findProductLine = PL.find(
        (p) => p.ProductLineCode === ProductLineCode
      );
      if (findProductLine && findProductLine.PointCodes.length > 0) {
        findSelf = findProductLine?.PointCodes.find(
          (f) => f.PointCode === PointCode
        );
      }

      const Put_Rule = findSelf?.Put_Rule;
      const SortType = findSelf?.SortType;
      const specialPointCode = findSelf?.specialPointCode;
      const isExistBlock = findSelf?.isExistBlock;
      console.log("SortType", SortType);
      this.Put_Rule = Put_Rule;
      localStorage.setItem("Put_Rule", Put_Rule);
      return { SortType, isExistBlock, specialPointCode };
    },
    async getRemoteurl() {
      const params = {
        UserId: this.loginForm.userName,
      };
      let [ERR, GRES] = await api.getRemoteurlAPI(params);
      if (GRES.code === 0) {
        sessionStorage.setItem("RemoteUrl", GRES?.RemoteUrl);
        PrintInit(sessionStorage.getItem("userName"));
      }
    },
    submitForm() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          const params = {
            userId: this.loginForm.userName,
            userRoleIds: this.loginForm.Permission.join(","),
            // userRoleIds: "SYSADMIN,READONLY,PDAADMIN",
            createBy: "djj",
          };
          let [ERR, LRES] = await api.UserRolesPost(params);
          if (LRES.code === 0) {
            this.$message.success(
              `User: 【${
                this.loginForm.userName
              }】 set to 【${this.loginForm.Permission.join(",")}】 success`
            );
          }
        }
      });
    },
    // submitForm() {
    //   this.$refs.loginForm.validate((valid) => {
    //     if (valid) {
    //       PrevLoading.start();
    //       const params = {
    //         UserName: this.loginForm.userName,
    //         Password: encrypt(this.loginForm.password, this.PublicKey),
    //       };
    //       // const params = {
    //       // 	UserName: this.loginForm.userName,
    //       // 	Password: this.loginForm.password
    //       // }
    //       console.log("登录传参:", params);
    //       signIn(params)
    //         .then((res) => {
    //           console.log(res);
    //           if (res.data.Code == 0) {
    //             const UserId = this.loginForm.userName;
    //             sessionStorage.setItem("UserId", UserId);
    //             const AccessToken = res.data.Data.AccessToken;
    //             const RefreshToken = res.data.Data.RefreshToken;
    //             setAccessToken(AccessToken);
    //             setRefreshToken(RefreshToken);
    //             this.getMenu();
    //           } else {
    //             this.fullscreenLoading = false;
    //             PrevLoading.done();
    //             this.$message.error(res.data.messsage);
    //           }
    //         })
    //         .catch((error) => {
    //           throw error;
    //         });
    //     } else {
    //       return false;
    //     }
    //   });
    // },
  },
  destroyed() {
    clearInterval(this.time.fun);
    window.removeEventListener("keydown", this.onKeyUp, false);
  },
};
</script>

<style scoped lang="scss">
// @font-face {
//   font-family: text-security-disc;
//   src: url("https://raw.githubusercontent.com/noppa/text-security/master/dist/text-security-disc.woff");
// }

// input.password {
//   font-family: text-security-disc;
//   -webkit-text-security: disc;
// }

.login {
  height: 100%;
  width: 100%;
  overflow: hidden;
  display: flex;
  position: relative;
  // background: url(../assets/image/bg-login.png) no-repeat;
  // background: url(../../assets/image/agvbg.jpg) no-repeat;
  background-size: 100% 100%;
  .login-weaper {
    margin: auto;
    height: 500px;
    display: flex;
    box-sizing: border-box;
    position: relative;
    z-index: 1;
    border: none;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    .login-left {
      width: 491px;
      padding: 20px;
      font-size: 16px;
      color: #fff;
      position: relative;
      background-color: rgba(64, 158, 255, 0.8);
      display: flex;
      flex-direction: column;
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
      .login-time {
        width: 100%;
        color: #fff;
        opacity: 0.9;
        font-size: 14px;
        overflow: hidden;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .lang_span {
          .iconfont {
            color: #fff;
            font-size: 30px !important;
          }
        }
      }
      .login-left-box {
        flex: 1;
        overflow: hidden;
        position: relative;
        z-index: 1;
        display: flex;
        align-items: center;
        padding: 80px 45px;
        .logo {
          font-size: 22px;
          margin-bottom: 15px;
        }
        .title {
          color: #fff;
          font-weight: 300;
          letter-spacing: 2px;
          font-size: 16px;
        }
        .msg {
          color: #fff;
          font-size: 14px;
          margin-top: 35px;
          .login_type_radio.el-radio-group {
            display: flex;
            flex-direction: column;
            .el-radio {
              color: #fff !important;
              margin-top: 10px;
              ::v-deep .el-radio__label {
                font-size: 16px;
              }
            }
            .el-radio.is-checked {
              ::v-deep .el-radio__label {
                color: #7fff00 !important;
              }
              ::v-deep .el-radio__input.is-checked .el-radio__inner {
                border-color: #7fff00 !important;
                background: #7fff00 !important;
              }
            }
          }
          .msg-author {
            opacity: 0.6;
            span:last-of-type {
              margin-left: 15px;
            }
          }
          .msg-txt {
            margin-top: 15px;
            line-height: 22px;
          }
        }
      }
    }
    .login-right {
      width: 50vw;
      padding: 20px;
      position: relative;
      align-items: center;
      display: flex;
      background-color: rgba(255, 255, 255, 1);
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
      .login-main {
        margin: 0 auto;
        width: 70%;
        .login-title {
          color: #333;
          margin-bottom: 40px;
          font-weight: 500;
          font-size: 22px;
          text-align: center;
          letter-spacing: 4px;
        }
        .login-form {
          margin: 10px 0;
          i {
            color: #333;
          }
          .el-select {
            width: 100%;
          }
          .el-form-item {
            margin-bottom: 20px !important;
            .login-code {
              display: flex;
              align-items: center;
              justify-content: space-around;
              margin: 0 0 0 10px;
              user-select: none;
              .login-code-img {
                margin-top: 2px;
                width: 100px;
                height: 38px;
                border: 1px solid #dcdfe6;
                color: #333;
                font-size: 14px;
                font-weight: 700;
                letter-spacing: 5px;
                line-height: 38px;
                text-indent: 5px;
                text-align: center;
                cursor: pointer;
                transition: all ease 0.2s;
                border-radius: 4px;
                &:hover {
                  border-color: #c0c4cc;
                  transition: all ease 0.2s;
                }
              }
            }
            .login-submit {
              width: 100%;
              //height: 45px;
              letter-spacing: 2px;
              font-weight: 300;
            }
          }
        }
        .login-menu {
          margin-top: 30px;
          width: 100%;
          text-align: left;
          a {
            color: #999;
            font-size: 12px;
            margin: 0 8px;
            text-decoration: none;
            &:hover {
              color: #1e9fff;
              text-decoration: underline;
            }
          }
        }
      }
    }
  }
}
</style>
